// pages/login/login.js
const app = getApp()
const Button = wx.getMenuButtonBoundingClientRect()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title:'选择商户',
    merchantList:[],
    cacheMerchantlist:[],
    phoneNum:'',
    showActionsheet:false,
    navBarHeight: app.globalData.navBarHeight,
    Button: Button,
    CDNPATH: app.globalData.CDNPATH,
    code: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log('code', res.code)
        this.setData({
          code: res.code
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getPhoneNumber: function (e) {
    console.log(e,'e====')
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      wx.login({
        success: res => {
          this.setData({
            code: res.code
          })
          // 拿手机号 获取商户列表
          this.getMerchantList(e)
        }
      })
    }
  },
  getMerchantList (e) {
    const { code } = this.data
    // 获取手机号码
    app.api.getPhoneNumber({
      url: '/ailearning/getVxTel',
      data: {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        code
      }
    }).then(res=>{
      const phoneNum = res.data
      app.api.getMerchantList({
        url: '/ailearning/getAffiliatedMerchants',
        data: {
          account:phoneNum,
          platform: 'ailearning',
        }
      }).then(res=>{
        console.log(res,'res=========')
        const list = res.data.list || res.list || []
        // const list = [{id:'2011410177141379456',merchantName:'长城'},{id:'2011410177141379456',merchantName:'长城'}]
        const _list = list.reduce((p,c)=>{
          p.push(c.merchantName)
          return p
        },[])
        this.setData({
          cacheMerchantlist:list,
          merchantList:_list,
          phoneNum:phoneNum
        })
        if(list.length>1) {
          this.setData({
            showActionsheet:true
          })
        }else{
          if(list.length>0){
            console.log('111111======')
            const merchantId = list[0].id
            this.login(phoneNum,merchantId)
          }else{
            wx.showModal({
              content: '账号不存在',
              showCancel: false
            })
          }
        }
      })
    })
  },
  getPermission () {
    return new Promise((resolve,reject)=>{
      app.api.get({
        url:'getUserAppResources'
      }).then(res=>{
        const roles = res || []
        if(roles.length >0){
          const permissionCodes = roles.reduce((p,c)=>{
            p.push(c.code)
            return p
          },[])
          app.globalData.permissionCodes = permissionCodes
          wx.setStorageSync("permissionCodes", JSON.stringify(permissionCodes))
          console.log(app.globalData.permissionCodes,'app.globalData.permissionCodes')
          resolve()
        }
      }).catch((err)=>{
        reject(err)
      })
    })
  },
  login(phoneNum,merchantId) {
    app.api.login({
      url: '/ailearning/vxLogin',
      data: {
        phoneNum: phoneNum,
        merchantId
      }
    }).then(res => {
      app.globalData.userInfo = res.data
      console.log(app.globalData.userInfo,'userInfo====');
      wx.setStorageSync("isLogin", true)
      wx.setStorageSync("token", res.data.token)
      wx.setStorageSync("userInfo", JSON.stringify(res.data))
      console.log(res.data.roleType === 'admin')
      this.getPermission().then(()=>{
        app.api.post({
          url: 'operation_add',
          data: {
            operationType: 'activity'
          }
        })
        app.api.post({
          url: 'vx_feedback_hasNewMsgTips'
        }).then(res => {
          if (res.hasNewMsg > 0) {
            wx.showTabBarRedDot({
              index: 4,
              fail: res => {
                console.log(res);
              }
            })
          } else {
            wx.hideTabBarRedDot({
              index: 4,
              fail: res => {
                console.log(res);
              }
            })
          }
        })
        wx.switchTab({
          url: `/pages/home-page/index/index`,
        })
      }).catch((err)=>{
        console.log(err,'err=====');
        const msg = err.data.error_response.msg
        wx.showModal({
          content: msg,
          showCancel: false
        })
      })
    }, () => {
      // 重新登录防止code无效
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          this.setData({
            code: res.code
          })
        }
      })
    })
  },
  selectAction (e) {
    const index = e.detail
    const {cacheMerchantlist,phoneNum} = this.data
    console.log(index,'index=====');
    const merchantId = cacheMerchantlist[index].id
    this.login(phoneNum,merchantId)
  },
  typePhone: function (e) {
    wx.navigateTo({
      url: `/pages/login/phone/phone`,
    })
  },
})